package red.yancloud.www.base

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.LinearLayoutCompat
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import kotlinx.android.synthetic.main.custom_empty_view.*
import red.yancloud.www.R
import red.yancloud.www.util.*

import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.Random

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/13 10:19
 * E_Mail：yh131412hys@163.com
 * Describe：基类WebViewActivity
 * Change：
 * @Version：V1.0
 */
abstract class BaseWebViewActivity : BaseActivity(), View.OnClickListener {

    private val TAG = "BaseWebViewActivity"

    protected lateinit var mWebView: WebView
    protected lateinit var errorLayout: LinearLayoutCompat
    protected lateinit var mRefreshLayout: SmartRefreshLayout
    protected lateinit var title: AppCompatTextView

    protected lateinit var mHandler: Handler
    protected lateinit var mUrl: String

//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_base_web_view);
//    }

    override fun initData() {

        mUrl = intent.getStringExtra("url")
        Log.d(TAG, "initData: $mUrl")
    }

    override fun configViews() {

        title = findViewById(R.id.title_tv)
        mWebView = findViewById(R.id.webViewActivity_webView)
        mRefreshLayout = findViewById(R.id.webViewActivity_refreshLayout)
        errorLayout = findViewById(R.id.webViewActivity_errorView)
        findViewById<View>(R.id.reload).setOnClickListener(View.OnClickListener {
            if (!NetworkUtils.isConnected(mContext)) {
                errorLayout.visibility = View.VISIBLE
                empty_view_tv.setText(R.string.no_network_view_hint)
                ToastUtils.toastNetErrorMsg()
                return@OnClickListener
            }
            loadWeb()
        })

        val delta = Random().nextInt(7 * 24 * 60 * 60 * 1000)
        val mClassicsHeader = mRefreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis() /*- delta*/))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))

        mRefreshLayout.setOnRefreshListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(Runnable {

//                mAdapter.refresh(initData());
//                refreshLayout.finishRefresh();
//                refreshLayout.resetNoMoreData();//setNoMoreData(false);

                if (!NetworkUtils.isConnected(mContext)) {
                    errorLayout.visibility = View.VISIBLE
                    empty_view_tv.setText(R.string.no_network_view_hint)
                    ToastUtils.toastNetErrorMsg()
                    mRefreshLayout.finishRefresh()
                    return@Runnable
                }
                loadWeb()
            }, 1000)
        }

        mHandler = Handler()
        title.text = getString(R.string.content_acquisition)
        webSetting()
        mWebView.webViewClient = MyWebViewClient()
        mWebView.webChromeClient = MyChromeClient()

        if (!NetworkUtils.isConnected(mContext)) {
            errorLayout.visibility = View.VISIBLE
            ToastUtils.toastNetErrorMsg()
            return
        }
        loadWeb()
    }

    private fun loadWeb() {
        Log.d(TAG, "loadWeb: " + UrlUtils.markSignUrl(mUrl))
        mWebView.loadUrl(mUrl)
    }

    /**
     * 网页配置参数设置
     */
    @SuppressLint("SetJavaScriptEnabled")
    private fun webSetting() {

        mWebView.isFocusable = true
        mWebView.setBackgroundColor(0x00ffffff)
        mWebView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY

        val webSetting: WebSettings = mWebView.settings
////        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
////            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
////        }
//        webSetting.javaScriptCanOpenWindowsAutomatically = true
//        webSetting.javaScriptEnabled = true
//        // 是否支持viewport属性，默认值 false
//        // 页面通过`<meta name="viewport" ... />`自适应手机屏幕
//        webSetting.useWideViewPort = true
//        // 是否使用overview mode加载页面，默认值 false
//        // 当页面宽度大于WebView宽度时，缩小使页面宽度等于WebView宽度
//        webSetting.loadWithOverviewMode = true
//        // 布局算法
//        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
//
//        // 缩放(zoom)
//        webSetting.setSupportZoom(true)          // 是否支持缩放
//        webSetting.builtInZoomControls = true // 是否使用内置缩放机制
//        webSetting.displayZoomControls = true  // 是否显示内置缩放控件

        webSetting.javaScriptEnabled = true
        webSetting.javaScriptCanOpenWindowsAutomatically = true
        webSetting.allowFileAccess = true
        webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSetting.setSupportZoom(true)
        webSetting.builtInZoomControls = true
        webSetting.useWideViewPort = true
        webSetting.setSupportMultipleWindows(true)
        // 当页面宽度大于WebView宽度时，缩小使页面宽度等于WebView宽度
        webSetting.loadWithOverviewMode = true
        webSetting.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSetting.domStorageEnabled = true
        webSetting.setGeolocationEnabled(true)
        webSetting.setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.pluginState = WebSettings.PluginState.ON_DEMAND
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.cacheMode = WebSettings.LOAD_NO_CACHE
        //允许混合加载
        webSetting.setAllowUniversalAccessFromFileURLs(true)

        // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        // settings 的设计
        addJavaScriptInterface()
    }

    abstract fun addJavaScriptInterface()

    /**
     * @Author：风不会停息 on 2019/2/15 11:48
     * E_Mail：yh131412hys@163.com
     * @Description：监听网页状态
     * @Change：
     * @Version：V1.0
     */
    private inner class MyWebViewClient : WebViewClient() {

        //        @Override
        //        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        //            String url = request.getUrl().toString();
        //            view.loadUrl(url);
        //            return super.shouldOverrideUrlLoading(view, request);
        //        }
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            Log.d(TAG, "shouldOverrideUrlLoading: $url")

            if (url.endsWith(".docx") || url.endsWith(".pdf")) {

//                https://view.officeapps.live.com/op/view.aspx?src=
//                https://view.officeapps.live.com/op/view.aspx?src=
                AppUtils.openBrowser(mContext, url)
            }else{

                view.loadUrl(url)
            }
            return true
        }

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            Log.d(TAG, "onPageStarted: $url")

            if (!(mContext as Activity).isFinishing) {
                loadingDialog.show()
            }
        }

        override fun onPageFinished(view: WebView, url: String) {

            if (NetworkUtils.isConnected(mContext)) {

                errorLayout.visibility = View.GONE
            } else {

                errorLayout.visibility = View.VISIBLE
                ToastUtils.toastNetErrorMsg()
            }
            if (null == mWebView.title) {
                return
            }

            Log.d(TAG, "onPageFinished: " + mWebView.title)
            if ("" != mWebView.title && mWebView.title.length > 20) {
                title.text = ""
            }else{
                title.text = mWebView.title
            }
            mRefreshLayout.finishRefresh()
            if (!(mContext as Activity).isFinishing) {
                loadingDialog.dismiss()
            }
        }

        //        @Override
        //        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        //            super.onReceivedError(view, request, error);
        //            webView.loadUrl("file:///android_asset/repair/repair.html");
        //            webView.getSettings().setLayoutAlgorithm( WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //
        //            title.setText("获取失败");
        //
        //            if (null != loadingDialog && !isFinishing()) {
        //                LoadingDialog.cancel();
        //                loadingDialog = null;
        //            }
        //        }

        override fun onReceivedError(
            view: WebView, errorCode: Int,
            description: String, failingUrl: String) {
            super.onReceivedError(view, errorCode, description, failingUrl)

            //            webView.loadUrl("file:///android_asset/repair/repair.html");
            //            webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

            title.text = "获取失败"

            if (!isFinishing) {
                loadingDialog.dismiss()
            }
        }

        fun onReceivedSslError(
            view: WebView, handler: SslErrorHandler,
            error: SslError
        ) {

            Log.d(TAG, "onReceivedSslError: ")
            handler.proceed()
        }
    }

    /**
     * @Author：风不会停息 on 2019/2/15 11:47
     * E_Mail：yh131412hys@163.com
     * @Description：监听网页加载进度
     * @Change：
     * @Version：V1.0
     */
    private inner class MyChromeClient : WebChromeClient()
}
